package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.XiaoAnQianBaoParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.List;
import java.util.Map;

@Service
public class XiaoAnQianBaoReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiIv = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        Integer planId = jsonObjectParamContent.getInteger("plan_id");//计划id
        String orderNum = jsonObjectParamContent.getString("order_num");//订单号
        String encryption = jsonObjectParamContent.getString("encryption");
//        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(encryption);
        String paramContentData = null;
        try {
            paramContentData = decrypt(encryption, apiSecret, apiIv);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject2 = JSONObject.parseObject(paramContentData);
        JSONObject jsonObject = jsonObject2.getJSONObject("encryption");
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("name")) ||
                StrUtil.isEmpty(jsonObject.getString("md5")) ||
                jsonObject.getInteger("sex") == null ||
                jsonObject.getInteger("age") == null ||
                jsonObject.getInteger("loan") == null ||
                StrUtil.isEmpty(jsonObject.getString("city")) ||
                jsonObject.getInteger("zhimafen") == null ||
                jsonObject.getInteger("huabei") == null ||
                jsonObject.getInteger("baitiao") == null ||
                jsonObject.getInteger("credit") == null ||
                jsonObject.getInteger("house") == null ||
                jsonObject.getInteger("car") == null ||
                jsonObject.getInteger("fund") == null ||
                jsonObject.getInteger("business") == null ||
                jsonObject.getInteger("social") == null ||
                StrUtil.isEmpty(jsonObject.getString("ip"))){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        jsonObject.put("orderNum",orderNum);
        String paramContentData1 = JSON.toJSONString(jsonObject);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);


        // 获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(userDataParam.getCity());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiIv = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        Integer planId = jsonObjectParamContent.getInteger("plan_id");//计划id
        String orderNum = jsonObjectParamContent.getString("order_num");//订单号
        String encryption = jsonObjectParamContent.getString("encryption");
//        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(encryption);
        String paramContentData = null;
        try {
            paramContentData = decrypt(encryption, apiSecret, apiIv);
        } catch (Exception e) {
            e.printStackTrace();
        }


        JSONObject jsonObject2 = JSONObject.parseObject(paramContentData);
        JSONObject jsonObject1 = jsonObject2.getJSONObject("encryption");
        jsonObject1.put("orderNum",orderNum);
        String paramContentData1 = JSON.toJSONString(jsonObject1);

        XiaoAnQianBaoParam xiaoAnQianBaoParam = JSON.parseObject(paramContentData1, XiaoAnQianBaoParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);

        userDataParam.setMobile(xiaoAnQianBaoParam.getMobile());
        userDataParam.setRealName(xiaoAnQianBaoParam.getName());

        String orderNum1 = xiaoAnQianBaoParam.getOrderNum();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), orderNum1);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "客户可进件！");

        JSONObject dataObject = new JSONObject();
        dataObject.put("price", String.valueOf(sourceBaseInfo.getPriceAmount()));

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())) {
            dataObject.put("company", thirdBaseInfo.getProductName());
            dataObject.put("company_name", thirdBaseInfo.getCompanyName());
        }else{
            dataObject.put("company", merchantBaseInfo.getCompanyName());
            dataObject.put("company_name", merchantBaseInfo.getInfoName());
        }

        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                returnObject.put("data",new JSONObject());
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        returnObject.put("data",new JSONObject());
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        XiaoAnQianBaoParam xiaoAnQianBaoParam = JSON.parseObject(paramContent, XiaoAnQianBaoParam.class);
        UserDataParam userDataParam = new UserDataParam();
        userDataParam.setOutOrderNo(xiaoAnQianBaoParam.getOrderNum());

        userDataParam.setMobileMd5(xiaoAnQianBaoParam.getMd5());

        userDataParam.setMobile(xiaoAnQianBaoParam.getMobile());

        userDataParam.setRealName(xiaoAnQianBaoParam.getName());

        if (xiaoAnQianBaoParam.getSex() == 1){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }

        userDataParam.setAge(xiaoAnQianBaoParam.getAge());

        userDataParam.setCity(xiaoAnQianBaoParam.getCity());

        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());

        Integer loan = xiaoAnQianBaoParam.getLoan();
        if (loan == 5) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (loan == 4) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (loan == 3) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (loan == 2) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer zhimafen = xiaoAnQianBaoParam.getZhimafen();
        if (zhimafen == 1){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (zhimafen == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (zhimafen == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        Integer huabei = xiaoAnQianBaoParam.getHuabei();
        if (huabei == 3){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb003.getValue());
        }

        Integer baitiao = xiaoAnQianBaoParam.getBaitiao();
        if (baitiao == 3){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }else {
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt003.getValue());
        }

        Integer credit = xiaoAnQianBaoParam.getCredit();
        if (credit == 2){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
        }

        Integer house = xiaoAnQianBaoParam.getHouse();
        if (house == 0){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }

        Integer car = xiaoAnQianBaoParam.getCar();
        if (car == 0){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        Integer fund = xiaoAnQianBaoParam.getFund();
        if (fund == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer social = xiaoAnQianBaoParam.getSocial();
        if (social == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else{
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        String ip = xiaoAnQianBaoParam.getIp();
        if (StringUtils.isNotEmpty(ip)){
            userDataParam.setUserIp(ip);
        }else {
            userDataParam.setUserIp("127.0.0.1");
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());

        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());

        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());

        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());

        userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());

        userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }

    public static String encrypt(String data,String appCode,String iv) throws Exception {
        byte[] encrpyted = tripleDES(Cipher.ENCRYPT_MODE, data.getBytes(StandardCharsets.UTF_8), appCode.getBytes(),iv);
        return new String(Base64.encodeBase64(encrpyted));
    }

    public static String decrypt(String data,String appCode,String iv) throws Exception {
        byte[] decoded = Base64.decodeBase64(data); // Base64 解码
        byte[] decrypted = tripleDES(Cipher.DECRYPT_MODE, decoded, appCode.getBytes(),iv);// 3DES 解密
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    private static byte[] tripleDES(int opmode, byte[] data, byte[] secretKey,String VI) throws Exception {
        return cipher("DESede", "DESede/CBC/PKCS5Padding", opmode, data, VI.getBytes(), secretKey);
    }

    private static byte[] cipher(String algorithm, String transformation, int opmode, byte[] data, byte[] iv,
                                 byte[] secretKey) throws Exception {
        Key key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESedeKeySpec(secretKey));
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opmode, key, spec);
        return cipher.doFinal(data);
    }


}
